package com.jshongli.myapplication.inspect;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jshongli.myapplication.R;
import com.jshongli.myapplication.base.BaseActivity;
import com.jshongli.myapplication.common.callback.ResponseCallback;
import com.jshongli.myapplication.common.utils.AccountManager;
import com.jshongli.myapplication.common.utils.AppManager;
import com.jshongli.myapplication.common.utils.CroodUtils;
import com.jshongli.myapplication.common.utils.DateUtils;
import com.jshongli.myapplication.common.utils.ParseUtils;
import com.jshongli.myapplication.common.utils.ToastUtils;
import com.jshongli.myapplication.common.utils.URLUtils;
import com.jshongli.myapplication.common.utils.UtilPreferences;
import com.jshongli.myapplication.model.inspect.EventBean;
import com.jshongli.myapplication.model.task.ReplyBean;
import com.jshongli.myapplication.model.task.TaskBean;
import com.jshongli.myapplication.task.TaskReplyActivity;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.zhy.http.okhttp.OkHttpUtils;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Request;

public class ReplyEventActivity extends BaseActivity {

    EventBean.DATA item;

    @BindView(R.id.tv_sjlx)
    TextView tv_sjlx;
    @BindView(R.id.tv_glzjd)
    TextView tv_glzjd;
    @BindView(R.id.tv_sjnr)
    TextView tv_sjnr;
    @BindView(R.id.tv_sjzt)
    TextView tv_sjzt;
    @BindView(R.id.tv_sjsj)
    TextView tv_sjsj;
    @BindView(R.id.tv_szwz)
    TextView tv_szwz;
    @BindView(R.id.tv_clr)
    TextView tv_clr;
    @BindView(R.id.nineGrid)
    NineGridView nineGrid;
    @BindView(R.id.ll_xczp)
    LinearLayout ll_xczp;
    @BindView(R.id.ifcl)
    LinearLayout ifcl;
    @BindView(R.id.ll_fk)
    LinearLayout ll_fk;

    @BindView(R.id.recy)
    RecyclerView recy;

    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_reply_event;
    }

    @Override
    protected void initData() {
        super.initData();

        item = (EventBean.DATA)getIntent().getSerializableExtra("item");
    }

    @Override
    protected void initView() {
        super.initView();
        initToolbarBack(mToolbar);
        mToolbar.setTitle("事件详情");

        if(item.userId != null)
        {
            ifcl.setVisibility(View.VISIBLE);
            tv_clr.setText(item.userName);
            if(UtilPreferences.getString(mContext,"userid").equals(String.valueOf(item.userId)) && item.status != 3)
            {
                initTvRightText(mToolbar,"反馈",null);
            }
        }else
        {
            if(UtilPreferences.getString(mContext,"roleIds").contains("1"))
            {
                initTvRightText(mToolbar,"派发",null);
            }

            ifcl.setVisibility(View.GONE);
        }

        mRefreshLayout.setColorSchemeResources(R.color.refresh_blue,
                R.color.refresh_red, R.color.refresh_blue, R.color.refresh_red);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData();
            }
        });

        setCommon();

        getData();
    }

    private void setCommon() {
        tv_sjlx.setText(item.type);
        tv_glzjd.setText(item.cable);
        tv_sjnr.setText(item.content);
        tv_sjzt.setText(ParseUtils.getSJZT(String.valueOf(item.status)));
        tv_sjzt.setTextColor(ParseUtils.getSJZT_color(mContext, String.valueOf(item.status)));
        tv_sjsj.setText(item.createTime);
        tv_szwz.setText(!TextUtils.isEmpty(item.lonLat)   ? item.lonLat:"");

        if ((item.picPath1 != null && item.picPath1.length() > 0) || (item.picPath2 != null && item.picPath2.length() > 0) || (item.picPath2 != null && item.picPath2.length() > 0)) {

            ll_xczp.setVisibility(View.VISIBLE);
        } else {
            ll_xczp.setVisibility(View.GONE);
        }

        List<String> pics = new ArrayList<>();
        pics.add(item.picPath1);
        pics.add(item.picPath2);
        pics.add(item.picPath3);
        if (pics.size() > 0) {
            setPics(pics, nineGrid);
        }

    }

    //region HTTP -- 处理过程
    public void getData() {
        String url = URLUtils.URLNoToken("manageAPI/bizReply/getList");
        Map<String, String> map = new HashMap<>();
        map.put("workId", String.valueOf(item.id));
        OkHttpUtils
                .get()
                .url(url)
                .params(map)
                .addHeader("Authorization", AccountManager.getToken())
                .tag(this)
                .build()
                .execute(new ResponseCallback<ReplyBean>(mContext) {

                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        mRefreshLayout.setRefreshing(true);
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        mRefreshLayout.setRefreshing(false);
                        if(mProcessData.size()>0){
                            recy.setVisibility(View.VISIBLE);
                            ll_fk.setVisibility(View.VISIBLE);
                        }else {
                            recy.setVisibility(View.GONE);
                            ll_fk.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onResponse(ReplyBean response, int id) {
                        super.onResponse(response, id);
                        if (response.code == 0) {
                            if (response.data != null) {
                                mProcessData = response.data;
                            }
                        }  else {
                            ToastUtils.show(mContext, "查询出错");
                        }




                        if (mAdapter == null) {
                            initRecy();
                        } else {
                            mAdapter.setNewData(mProcessData);
                        }
                    }

                });
    }
    //endregion

    //region Recy -- 处理过程
    BaseQuickAdapter<ReplyBean.DATA, BaseViewHolder> mAdapter;
    List<ReplyBean.DATA> mProcessData = new ArrayList<>();

    private void initRecy() {
        mAdapter = new BaseQuickAdapter<ReplyBean.DATA, BaseViewHolder>(R.layout.list_task_process_item, mProcessData) {
            @Override
            protected void convert(BaseViewHolder helper, ReplyBean.DATA item) {
                helper.setText(R.id.tv_tm, DateUtils.formatString(item.createTime,"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd\nHH:mm:ss"))
                        .setText(R.id.tv_ry,item.createName);
                helper.setText(R.id.tv_zt,item.statusName);
                helper.setText(R.id.tv_content, item.reply);

            }
        };

        recy.setAdapter(mAdapter);
        recy.setLayoutManager(new LinearLayoutManager(mContext));
    }
    //endregion

    //region NineGridView -- 显示图片
    private void setPics(List<String> pics, NineGridView nineGrid) {

        if (pics.size() > 0) {
            ArrayList<ImageInfo> imageInfos = new ArrayList<>();
            if (pics != null) {
                for (String pic : pics) {
                    ImageInfo info = new ImageInfo();
                    Log.e("11111", URLUtils.XCXJiMg(pic));
                    info.setThumbnailUrl(URLUtils.XCXJiMg(pic));
                    info.setBigImageUrl(URLUtils.XCXJiMg(pic));
                    imageInfos.add(info);
                }

            }
            nineGrid.setSingleImageRatio(1.5f);
            nineGrid.setGridSpacing(15);
            nineGrid.setAdapter(new NineGridViewClickAdapter(mActivity, imageInfos));

        } else {
            nineGrid.setVisibility(View.GONE);
        }
    }
    //endregion

    //region 点击导航弹出选择
    private void showBottomDialog(String lat, String lng) {
        //1、使用Dialog、设置style
        Dialog dialog = new Dialog(mContext, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(mContext, R.layout.dialog_navi_layout, null);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

        final LatLng baidupoint = CroodUtils.gcj02_To_Bd09(Double.valueOf(lat), Double.valueOf(lng));

        dialog.findViewById(R.id.tv_bai).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AppManager.isAvilible(mContext, "com.baidu.BaiduMap")) {//传入指定应用包名
                    try {
                        Intent intent = Intent.getIntent("intent://map/direction?" +
                                "destination=latlng:" + baidupoint.latitude + "," + baidupoint.longitude + "|name:我的目的地" +        //终点
                                "&mode=driving&" +          //导航路线方式
                                "&src=appname#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                        startActivity(intent); //启动调用
                    } catch (URISyntaxException e) {
                        Log.e("intent", e.getMessage());
                    }
                } else {//未安装
                    //market为路径，id为包名
                    //显示手机上所有的market商店
                    ToastUtils.show(mContext, "您尚未安装百度地图");

                    Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    if (intent.resolveActivity(mContext.getPackageManager()) != null) {
                        startActivity(intent);
                    }
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.tv_gao).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AppManager.isAvilible(mContext, "com.autonavi.minimap")) {
                    try {
                        Intent intent = Intent.getIntent("androidamap://navi?sourceApplication=BIG BOX 24&poiname=我的目的地&lat=" + lat + "&lon=" + lng + "&dev=0");
                        mContext.startActivity(intent);
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.show(mContext, "您尚未安装高德地图");
                    Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                }
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }
    //endregion

    @OnClick({R.id.tv_szwz})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_szwz:
                String[] jwdarr = item.lonLat.split(",");
                showBottomDialog(jwdarr[0],jwdarr[1]);
                break;

        }
    }

    @Override
    protected void onTvRightClicked() {
        super.onTvRightClicked();
        if(mToolbar.getTvRight().getText().equals("反馈")){
            Bundle bundle = new Bundle();
            bundle.putString("id",String.valueOf(item.id));
            bundle.putString("type","fk");
//        openActivity(TaskReplyActivity.class,bundle,false);
            openActivityForResult(TaskReplyActivity.class, bundle,8888);
        }else {
            Bundle bundle = new Bundle();
            bundle.putString("id",String.valueOf(item.id));
//        openActivity(TaskReplyActivity.class,bundle,false);
            openActivityForResult(DistributeActivity.class, bundle,5986);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==8888){
            //处理回调相关操作
            mRefreshLayout.setRefreshing(true);
            getData();

            String receivedData = data.getStringExtra("status");
            if(!receivedData.equals(String.valueOf(item.status)))
            {
                tv_sjzt.setText(ParseUtils.getSJZT(receivedData));
                tv_sjzt.setTextColor(ParseUtils.getSJZT_color(mContext, receivedData));
            }

            if(receivedData.equals("3"))
            {
                initTvRightText(mToolbar,"",null);
            }

            Intent intent = new Intent();
            setResult(8888, intent);

        }
        else if (resultCode==5986){
            String receivedData = data.getStringExtra("username");
            ifcl.setVisibility(View.VISIBLE);
            tv_clr.setText(receivedData);
            tv_sjzt.setText(ParseUtils.getSJZT("1"));
            tv_sjzt.setTextColor(ParseUtils.getSJZT_color(mContext, "1"));


            initTvRightText(mToolbar,"",null);

            Intent intent = new Intent();
            setResult(8888, intent);
        }
    }

}